package com.quyunshuo.module.home.fragment.home

import android.util.Log
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import com.google.android.material.tabs.TabLayoutMediator
import com.quyunshuo.edwincoffeetwo.common.ext.click
import com.quyunshuo.edwincoffeetwo.common.ui.BaseFragment
import com.quyunshuo.edwincoffeetwo.network.bean.ProjectTabItem
import com.quyunshuo.module.home.databinding.HomeFragmentHomeBinding
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch

/**
 * @author DBoy 2021/7/6 <p>
 * - 文件描述 : 测试fragment
 */
@AndroidEntryPoint
class HomeFragment : BaseFragment<HomeFragmentHomeBinding, HomeViewModel>() {
    private val TAG = "HomeFragment"
    override val mViewModel by viewModels<HomeViewModel>()
    private var tabLayoutMediator: TabLayoutMediator? = null // 保存中介者引用
    override fun createVB() = HomeFragmentHomeBinding.inflate(layoutInflater)
    override fun HomeFragmentHomeBinding.initListener() {

    }

    private var mProjectTabs  = mutableListOf<ProjectTabItem>()

    override fun HomeFragmentHomeBinding.initView() {

        mProjectTabs.add(0, ProjectTabItem(id = 0,"推荐"))

        // 设置ViewPager适配器

        // 绑定TabLayout与ViewPager2
        tabLayoutMediator = TabLayoutMediator(tabLayout, viewPager) { tab, position ->
            tab.text = mProjectTabs[position].name
        }.apply { attach() }
        etSearch.click {

        }

    }

    override fun onDestroyView() {
        mBinding.tabLayout.removeAllTabs()
        // 关键优化：释放资源
        tabLayoutMediator?.detach()
        mBinding.viewPager.adapter = null // 清空 ViewPager
        tabLayoutMediator =null //这样就没有内存问题了。
        Log.d(TAG, "onDestroyView: ")
        super.onDestroyView()
    }

    override fun initObserve() {
//        observeLiveData(mViewModel.firstData,::firstData)
      lifecycleScope.launch {

      }
    }

    private fun firstData(projectTabItems: MutableList<ProjectTabItem>?) {
        //拿到数据了，那么就要给adapter设置了。
        projectTabItems?.forEachIndexed {index,item->
            mProjectTabs.add(item)
        }
    }

    override fun initRequestData() {
        mViewModel.getData()
    }


}